package com.fanketly.funacg2.ui.viewmodels

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.entity.WorkEntity
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.paging.WorkPagingSource
import com.fanketly.funacg2.data.repo.FavouriteRepo
import com.fanketly.funacg2.utils.ToastUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class FavouriteViewModel @Inject constructor(private val repo: FavouriteRepo) : ViewModel() {

//    val uiState: StateFlow<List<WorkEntity>> =
//        getAll().stateIn(
//            scope = viewModelScope,
//            started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList()
//        )
    val pager: Flow<PagingData<WorkEntity>> = Pager(
        PagingConfig(
            pageSize = 20, initialLoadSize = 20, enablePlaceholders = true, maxSize = 200
        )
    ) {
        getAll()
    }.flow.cachedIn(viewModelScope)

    init {
        Log.d(TAG, "FavouriteViewModel_init")
    }

    private fun getAll() = repo.getAll()
    private val _isFavourite = mutableStateOf(false)
    val isFavourite: Boolean
        get() = _isFavourite.value


    fun checkFavourite(id: Int) {
        viewModelScope.launch {
            val favourite = repo.isFavourite(id)
            Log.i(TAG, "checkFavourite: ${favourite}")
            _isFavourite.value = favourite != null
        }
    }

    /**
     *@return  true为喜爱false为取消
     * */
    fun favouriteOrCancel(work: WorkList.Work): Boolean {
        return if (_isFavourite.value) {
            cancelFavourite(work.id)
            _isFavourite.value = false
            false
        } else {
            favourite(work)
            _isFavourite.value = true
            true
        }
    }

    private fun favourite(work: WorkList.Work) {
        viewModelScope.launch {
            repo.insert(WorkEntity(work.id, work.title, work.thumbnailCoverUrl))
        }
    }

    fun cancelFavourite(id: Int) {
        viewModelScope.launch {
            repo.delete(id)
        }
    }
}